package com.bw.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@RestController
@RequestMapping("auth")
public class AuthController {

    @Resource
    AuthenticationManager authenticationManager;

    @Autowired
    UserService userService;

    @RequestMapping("login")
    public Result login(@RequestBody User user){

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()+salt);

        authenticationManager.authenticate(authenticationToken);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getUsername,user.getUsername());

        User dbUser = userService.getOne(queryWrapper);

        String token = JWTUtils.createToken(dbUser.getId() + "", 12 * 60);

        return Result.success(token);
    }

    @Resource
    PasswordEncoder passwordEncoder;

    public static final String salt="2109a";

    @PostConstruct
    public void initPWD(){
        String pwd="123";
        String encode = passwordEncoder.encode(pwd + salt);
        System.out.println("初始化密码："+encode);
    }

}
